import { Component,ViewChild, ElementRef } from '@angular/core';

// const todos=[{
//   id:1,
//   title:"chif",
//   iscompleted:false
// },{
//   id:2,
//   title:"睡觉",
//   iscompleted:true
// },{
//   id:3,
//   title:"打豆豆",
//   iscompleted:false
// }]

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  // @ViewChild('inputBox') _el:ElementRef; 如果是一个input 点击获取焦点

  public todos :{
    id:number,
    title:string,
    iscompleted:boolean
  }[] = JSON.parse( localStorage.getItem("todos") ) || []
  public isediting:number = 0
  public visibility:string = null
 
  ngOnInit() { 
    // console.log(window.location.hash);
    this.hashChange()
    // console.log(this.visibility);
    window.onhashchange = ()=>{
      this.hashChange()
    }
  }
  ngDoCheck() {
    localStorage.setItem("todos", JSON.stringify(this.todos))
  }
  hashChange(){
    let hash = window.location.hash.substring(2);
    this.visibility =  hash ? hash : "all"
  }

  get newTodos (){
    let hash = this.visibility
    if(hash == "all"){
      return this.todos
    }else if(hash == "active"){
      return  this.todos.filter(t=> !t.iscompleted)
    }else if(hash == "completed"){
      return  this.todos.filter(t=> t.iscompleted)
    }
  }

  // 增加
  addTodo(e){
    var item = e.target.value;
    if(!item){
      return
    }
    var last = this.todos[this.todos.length-1]
   this.todos.push({
     id: last? last.id+1 : 1,
     title:item,
     iscompleted: false
   })
   e.target.value =""
    console.log(this.todos);
    
  }
  // 删
  delectTodo(index){
    this.todos.splice(index, 1)
  }
  //改
  edit(id){
    this.isediting = id
    // this._el.nativeElement.focus() 如果是一个input 点击获取焦点
  }
  // esc 取消编辑
  cancelEdit(e,todo){
    // Esc == 27
    if(e.keyCode == "27"){
      this.isediting = 0;
      e.target.value = todo.title 
    }

  }
  // 保存编辑
  saveEdit(e,todo){
    this.isediting = 0;
    todo.title = e.target.value
  }
  //删除所有
  delectAll(){
   this.todos = this.todos.filter(t => !t.iscompleted)
  }

  get allcompleted(){
    return this.todos.every(t => t.iscompleted)
  }

  set allcompleted(iscompleted){
    this.todos.forEach(t => t.iscompleted = iscompleted)
  }

  get remaningCount(){
    return this.todos.filter(t=> !t.iscompleted).length
  }

  get completedCount(){
    return this.todos.filter(t=> t.iscompleted).length > 0
  }


}
